import { socketService } from '@/utils/socket'
import { ElNotification } from 'element-plus'
import { messageStore } from '@/utils/messageStore'

export function bootstrapSocketAutoReconnect() {
	try {
		const GLOBAL_KEY = '__global_new_message_handler__'
		// If already bootstrapped, do nothing
		if ((window as any)[GLOBAL_KEY]) return

		const token = localStorage.getItem('token') || undefined
		const monitoredDevices: string[] = JSON.parse(localStorage.getItem('monitoredDevices') || '[]')
		if (!token && monitoredDevices.length === 0) return

		const socket = socketService.connect(token)

		// Register a single global handler
		const handler = (payload: any) => {
			try {
				if (payload?.is_self_message) return
				if (payload.device_id.startsWith("rag")) return
				if (payload.type !== 1) return
				const deviceId = payload.device_id || payload.room
				const fromWxId = payload.wx_id || payload.from || payload.from_user
				const content = payload.content || ''
				const accountNickname = payload.device_nickname || payload.accountNickname || payload.account_name || deviceId
				const senderNickname = payload.senderNickname || payload.sender_nickname || fromWxId
				const ts = typeof payload.timestamp === 'number' ? new Date(payload.timestamp * 1000) : (payload.timestamp ? new Date(payload.timestamp) : new Date())
				const timeStr = ts.toLocaleString()
				if (!deviceId || !fromWxId) return
				messageStore.incrementUnread(deviceId, fromWxId)
				const esc = (s: string) => String(s)
					.replace(/&/g, '&amp;')
					.replace(/</g, '&lt;')
					.replace(/>/g, '&gt;')
					.replace(/"/g, '&quot;')
					.replace(/'/g, '&#39;')
				const html = `
				  <div style="line-height:1.8;">
				    <div><strong>账号：</strong>${esc(accountNickname)}</div>
				    <div><strong>时间：</strong>${esc(timeStr)}</div>
				    <div><strong>发送者：</strong>${esc(senderNickname)}</div>
				    <div><strong>内容：</strong>${esc(content)}</div>
				  </div>
				`
				ElNotification({
					title: '新消息',
					message: html,
					dangerouslyUseHTMLString: true,
					position: 'bottom-left',
					duration: 1000
				})
			} catch (err) {
				console.error('global new_message handler error:', err)
			}
		}
		socket.on('new_message', handler)
		;(window as any)[GLOBAL_KEY] = handler

		// Rejoin saved device rooms
		for (const deviceId of monitoredDevices) {
			socketService.joinRoom(deviceId)
		}
	} catch (err) {
		console.error('bootstrapSocketAutoReconnect failed:', err)
	}
} 